package com.street.service.impl;

import com.street.constant.MessageConstant;
import com.street.context.BaseContext;
import com.street.dto.OrderDTO;
import com.street.entity.Cart;
import com.street.entity.OrderDetail;
import com.street.entity.Orders;
import com.street.exception.ShoppingCartBusinessException;
import com.street.mapper.CartMapper;
import com.street.mapper.OrderDetailMapper;
import com.street.mapper.OrderMapper;
import com.street.service.OrderService;
import com.street.vo.OrderSubmitVO;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    CartMapper shoppingCartMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrderDTO orderDTO) {
        //获取用户id
        Long userId= BaseContext.getCurrentId();
        //处理各种业务异常:用户购物车为空
        Cart shoppingCart=new Cart();
        //查找该用户的购物车是否为空
        shoppingCart.setUserId(userId);
        List<Cart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if(shoppingCartList==null||shoppingCartList.size()==0){
            //购物车为空,不能下单
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        Orders order=new Orders();
        //将dto里的数据拷贝进订单对象里
        BeanUtils.copyProperties(orderDTO,order);
        order.setUserId(userId);
        //订单状态为未付款
        order.setStatus(Orders.PENDING_PAYMENT);
        //支付状态为未付款
        order.setPayStatus(Orders.UN_PAID);
        //下单时间为现在
        order.setOrderTime(LocalDateTime.now());

        //清空该用户的购物车
        shoppingCartMapper.clear(userId,orderDTO.getShopId());
        //生成订单号(当前时间戳)
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        //插入到订单表，并且从订单表里返回了主键 订单id
        orderMapper.insert(order);
        Integer orderId=order.getId();
        //插入到明细表,将购物车里每一个对象都去插入一次
        List<OrderDetail> orderDetailList=new ArrayList<>();
        for (Cart cart : shoppingCartList) {
            //生成订单明细列表
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertDetail(orderDetailList);
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderTime(order.getOrderTime())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .id(orderId)
                .build();
        return orderSubmitVO;
    }
}
